import { nextTick } from '@tarojs/taro'
import { reactive, ref, watch } from 'vue'

export default function useToast() {
  const loading = ref(false)
  const loadingMsg = ref('努力加载中...')
  const duration = 2000

  const toast = reactive<ToastOptions>({
    msg: '',
    show: false,
    type: 'text',
  })
  watch(loading, (loadingVal) => {
    if (loadingVal) {
      toastLoading(loadingMsg.value)
    } else {
      toastClose()
    }
  })

  function toastLoading(msg: string = loadingMsg.value) {
    safeOpen(() => {
      toast.type = 'loading'
      toast.msg = msg
      toast.duration = 0
      toast.show = true
    })
  }

  function toastClose() {
    toast.show = false
  }

  // 避免与 loading 冲突，由于共用一个 Toast，而 loading 是不自动关闭的
  function safeOpen(cb) {
    if (toast.show) {
      toast.show = false

      nextTick(() => {
        cb()
      })
    } else {
      cb()
    }
  }

  return {
    toast,
    toastFail(msg: string) {
      safeOpen(() => {
        toast.type = 'fail'
        toast.msg = msg
        toast.show = true
        toast.duration = duration
      })
    },
    toastSuccess(msg: string) {
      safeOpen(() => {
        toast.type = 'success'
        toast.msg = msg
        toast.show = true
        toast.duration = duration
      })
    },
    toastLoading,
    toastClose,
    loading,
    loadingMsg,
  }
}
